<?php
/**
 * Created by PhpStorm.
 * User: wjj
 * Date: 2016/11/1
 */

namespace app\logic;


use app\models\Adv;
use yii;


class AdvLogic
{
    public static $input_type_list = ['下拉框','输入框','单选项','多选项'];

    public function getAdv($query = [], $page = 1, $limit = 10)
    {
        $adv = Adv::find();
        if(isset($query['adv_title'])){
            $adv->filterWhere(['LIKE','adv_title',$query['adv_title']]);
        }
        if(isset($query['adv_status'])){
            if($query['adv_status']!=2)
                $adv->filterWhere(['adv_status'=>$query['adv_status']]);
        }
        $count = $adv->count();
        $adv->orderBy('adv_sort asc, adv_id desc')
            ->offset(($page - 1) * $limit)->limit($limit);
        $lists = $adv->asArray()->all();
        $return = [
            'lists' => $lists,
            'pager' => [
                'total' => $count,
                'page' => $page,
                'limit' => $limit,
                'url' => 'adv/index',
                'query' => $query
            ]
        ];
        return $return;
    }

    public function editAdvById($id, $params, $uploadresult)
    {
        if(!$adv = Adv::findOne($id)) return false;
        $adv->adv_title = $params['adv_title'];
        $adv->adv_link = $params['adv_link'];
        $adv->adv_position = $params['adv_position'];
        $adv->start_time = $params['start_time'];
        $adv->end_time = $params['end_time'];
        $adv->adv_sort = $params['adv_sort'];
        $adv->adv_status = $params['adv_status'];
        $adv->add_time = date("Y-m-d H:i:s");
        if($uploadresult)
            $adv->adv_pic = $uploadresult;
        return $adv->save();
    }

    public function getById($id)
    {
        return Adv::find()->where(['adv_id' => $id])->asArray()->one();
    }


    public function saveStatus($id)
    {
        $adv = Adv::findOne($id);
        if($adv->status)
            $adv->status = 0;
        else
            $adv->status = 1;
        return $adv->save();
    }

    public function addAdv($params,$uploadresult){
        $adv = new Adv();
        $adv->adv_title = $params['adv_title'];
        $adv->adv_pic = $uploadresult;
        $adv->adv_link = $params['adv_link'];
        $adv->adv_position = $params['adv_position'];
        $adv->start_time = $params['start_time'];
        $adv->end_time = $params['end_time'];
        $adv->adv_sort = $params['adv_sort'];
        $adv->adv_status = $params['adv_status'];
        $adv->add_time = date("Y-m-d H:i:s");
        return $adv->save();
    }

    public function deleteById($id)
    {
        $adv = Adv::findOne($id);
        return $adv->delete();
    }


}
